﻿//------------------------------------------------------------------------------
//  
//------------------------------------------------------------------------------
#region Imported Namespaces
using System;
using System.IO;

using System.Xml.Serialization;
using System.Data;
//using System.Text;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net;
using System.Text;

using SSRS;
using PHSRAG.Insight21.Policy;
using Utils = PHSRAG.Insight21.InsightUtilities;
using PHSRAG.Insight21.SearchContext;
using UserContext = PHSRAG.Insight21.Context.UserContext;

#endregion

namespace PHSRAG.Insight21.Reports {

    public class sqlReportParameter
    {
        public string paraName;
        public string paraValue;
        public bool bLoadParameter=true;

        public sqlReportParameter()
        {
        }

        public sqlReportParameter(string pName, string pValue, bool bLoadP)
        {
            paraName = pName;
            paraValue = pValue;
            bLoadParameter = bLoadP;
        }
    }
    
    public abstract class sqlReport : System.Web.UI.Page, iReport
    {                 
        protected Policy.ICachePolicy pageCachePolicy;
        protected UserContext userContext;
        protected ICachePolicy cachePolicy;
        protected SearchCriteria searchCriteria=null;
        protected CommonSearchContext searchContext;
        protected string pageUrl;

        protected DateTime SalaryAsOfDate; // = (DateTime)((DataSet)cachePolicy.GetCachedObject(RefreshDatesControlKey)).Tables[0].Rows[0]["salaryAsOfDate"];
        protected DateTime glPostAsOfDate; // = (DateTime)((DataSet)cachePolicy.GetCachedObject(RefreshDatesControlKey)).Tables[0].Rows[0]["glPostAsOfDate"];
        protected DateTime POAPAsOfDate;    // = (DateTime)((DataSet)cachePolicy.GetCachedObject(RefreshDatesControlKey)).Tables[0].Rows[0]["poapAsOfDate"];

        private string rptName;

        public string rptFormat;
        protected const string pdfFormat = "pdf";
        protected const string excelFormat = "excel";

        private const string cReportTitle="reporttitle";
        private string rptTitle;
        protected sqlReportParameter pTitle = new sqlReportParameter();

        private const string cUsername = "username";
        private string rptUser;
        protected sqlReportParameter pUser = new sqlReportParameter();

        private const string cReportFiltercriteria = "filtercriteria";
        private string rptCriteria;
        protected sqlReportParameter pFilter = new sqlReportParameter();

        private const string cDataSource = "DataSource";
        private string sXmlData;
        protected sqlReportParameter pDataSource = new sqlReportParameter();

        private const string cRecordCount = "recordCount";
        private string rptResultCount;
        protected sqlReportParameter pRecordCount = new sqlReportParameter();

        private const string cWeburl = "weburl";
        private string cDefaultWebUrl = Utility.Settings.GetKeyValue(cWeburl, "insight.partners.org");
        private string rptUrl;
        protected sqlReportParameter pUrl = new sqlReportParameter();

        protected ArrayList registedParameters = new ArrayList();
        protected Hashtable htParameter = new Hashtable();
        protected const string RefreshDatesControlKey = "RefreshDates_D511306A-23E5-4d9b-AC38-17A2DEC0F6AE";
        protected DataSet rptSource;
        public bool doHashtable = false;
        public string CustomExcelFormat = "CustomExcelRenderCS";
        private bool mDoCustomExcelReport = false;
        
        public sqlReport(string pageUrl) {
            this.pageUrl = pageUrl;
            pageCachePolicy = (Policy.ICachePolicy)Session[Policy.Names.PageCachePolicyKey];
            cachePolicy = (Policy.ICachePolicy)Session[Policy.Names.CachePolicyKey];
            userContext = (UserContext)cachePolicy.GetCachedObject(UserContext.CacheKey);
            searchContext = (CommonSearchContext)cachePolicy.GetCachedObject(CommonSearchContext.CacheKey);
            if (searchContext != null)
            {
                searchCriteria = searchContext.GetSearchCriteria(pageUrl);
            }
            else
                throw (new Exception("Session Expired, Please Logout and Log In again"));

            DataSet RefreshDatesDS = cachePolicy.GetCachedObject(RefreshDatesControlKey) as DataSet;

            if (RefreshDatesDS != null)
            {
                SalaryAsOfDate = (DateTime)RefreshDatesDS.Tables[0].Rows[0]["salaryAsOfDate"];
                glPostAsOfDate = (DateTime)RefreshDatesDS.Tables[0].Rows[0]["glPostAsOfDate"];
                POAPAsOfDate = (DateTime)RefreshDatesDS.Tables[0].Rows[0]["poapAsOfDate"];
            }

            registedParameters.Add(pTitle);
            registedParameters.Add(pUser);
            registedParameters.Add(pFilter);
            registedParameters.Add(pDataSource);
            registedParameters.Add(pRecordCount);
            registedParameters.Add(pUrl);

        }

        public virtual string ReportName
        {
            get {
                return rptName;   
            }
            set
            {
                rptName = value;
            }
        }

        public virtual bool doCustomExcelReport
        {
            get
            {
                return mDoCustomExcelReport;
            }
            set
            {
                mDoCustomExcelReport = value;
            }
        }

        protected virtual DataSet reportSource
        {
            get
            {
                return rptSource;
            }
            set
            {
                rptSource = value;
            }
        }

        protected virtual string sXMLData
        {
            get
            {
                return sXmlData==null?(reportSource == null?"":getXMLDataWithSchema(rptSource)):sXmlData ;
            }
            set
            {
                sXmlData = value;
            }
        }

        protected virtual string reportTitle
        {
            get
            {
                return rptTitle;
            }
            set
            {
                rptTitle = value;
            }
        }

        protected virtual string reportUser
        {
            get
            {
                return rptUser==null?userContext.LastName + "," + userContext.FirstName:rptUser;
            }
            set
            {
                rptUser = value;
            }
        }

        protected virtual string reportCriteria
        {
            get
            {
                rptCriteria= rptCriteria ==null?loadCriteria(searchCriteria):rptCriteria ;
                rptCriteria= rptCriteria.Replace("|", ":");
                return rptCriteria;
            }
            set
            {
                rptCriteria = value;
            }
        }

        protected virtual string reportResultCount
        {
            get
            {
                if (rptSource != null)
                {
                    rptResultCount = (rptResultCount == null || rptResultCount == "") ? rptSource.Tables[0].Rows.Count.ToString() : rptResultCount;

                    if (int.Parse(rptResultCount) > 5000) throw new Exception("Please modify your search criteria to limit the data for the report download.");
                }
                else
                {
                    rptResultCount = (rptResultCount == null || rptResultCount ==""? "":rptResultCount);
                }
                return rptResultCount;

            }
            set
            {
                rptResultCount = value;
            }
        }

        protected virtual string reportUrl
        {
            get 
            {
                return rptUrl==null?cDefaultWebUrl:rptUrl;
            }
            set
            {
                rptUrl = value;
            }
        }
        
        public virtual ParameterValue[] setParameters(ref string rptName)
        {
            ParameterValue[] oInputPrms = new ParameterValue[5];
            // report title
            oInputPrms[0] = getReportTitleParameter(reportTitle);       //p1;

            oInputPrms[1] = getReportDataSource(sXMLData);

            // user name
            oInputPrms[2] = getReportUserParameter();

            ////GetSearchCriteria(cachePolicy);
            oInputPrms[3] = getReportFilter(reportCriteria);

            oInputPrms[4] = getReportResultCountParameter();

            return oInputPrms;


        }

        public virtual Hashtable setParameterHTable(ref string rptName)
        {
            prepareParamters();
            loadParameterHashTable();
            return htParameter;
        }

        public void loadParameterHashTable ()
        {
            foreach (sqlReportParameter p in registedParameters)
            {
                if (p.bLoadParameter == true)
                {
                    htParameter[p.paraName] = p.paraValue;
                }
            }
        }

        protected virtual void prepareParamters ()
        {
            if (pTitle.bLoadParameter)
            {
                pTitle.paraName = cReportTitle;
                pTitle.paraValue = reportTitle;
            }

            if (pUser.bLoadParameter)
            {
                pUser.paraName = cUsername;
                pUser.paraValue = reportUser;
            }

            if (pFilter.bLoadParameter)
            {
                pFilter.paraName = cReportFiltercriteria;
                pFilter.paraValue = reportCriteria;
            }

            if (pDataSource.bLoadParameter)
            {
                pDataSource.paraName = cDataSource;
                pDataSource.paraValue = sXMLData;
            }

            if (pRecordCount.bLoadParameter)
            {
                pRecordCount.paraName = cRecordCount;
                pRecordCount.paraValue = reportResultCount;
            }

            if (pUrl.bLoadParameter)
            {
                pUrl.paraName = cWeburl;
                pUrl.paraValue = reportUrl;
            }
        }

        protected virtual void setReportTitleParameter(string reportTitle)
        {
            htParameter.Add(cReportTitle, reportTitle);
        }

        protected virtual ParameterValue getReportTitleParameter (string reportTitle)
        {

            ParameterValue repTitle = new ParameterValue();
            repTitle.Name = cReportTitle;
            repTitle.Value = reportTitle ;
            return repTitle;
        }

        protected virtual void setReportDataSource(string sXMLData)
        {
            htParameter.Add("DataSource",sXMLData);
        }

        protected virtual ParameterValue getReportDataSource(string sXMLData)
        {
            ParameterValue p2 = new ParameterValue();
            p2.Name = "DataSource";
            p2.Value = sXMLData;
            return p2;
        }

        protected virtual void setReportUserParameter()
        {
            ////Username
            string username = userContext.LastName + "," + userContext.FirstName; //+ " (" + userContext.Username + ")"; //should we display the username as in at098 instead of Tarafder, Ajoy
            htParameter.Add(cUsername, username);
        }

        protected virtual ParameterValue getReportUserParameter()
        {
            ////Username
            ParameterValue p3 = new ParameterValue();
            p3.Name = cUsername;
            p3.Value = userContext.LastName + "," + userContext.FirstName; //+ " (" + userContext.Username + ")"; //should we display the username as in at098 instead of Tarafder, Ajoy
            return p3;
        }

        protected virtual void setReportFilter(string rptFilter)
        {
            htParameter.Add(cReportFiltercriteria, reportCriteria);
        }

        protected virtual ParameterValue getReportFilter(string rptFilter)
        {
            ParameterValue p4 = new ParameterValue();
            p4.Name = cReportFiltercriteria;
            p4.Value = rptFilter;
            return p4;
        }

        protected virtual void setReportResultCountParameter()
        {
           htParameter.Add (InsightUtilities.Constants.RecordCount,reportResultCount);
        }

        protected virtual ParameterValue getReportResultCountParameter()
        {
            ParameterValue p5 = new ParameterValue();
            p5.Name = InsightUtilities.Constants.RecordCount;
            p5.Value = reportResultCount;
            return p5;
        }

        /// <summary>
        ///  
        /// <param name="searchCriteria">Object containing search criteria.</param>
        /// <returns>A string representation of search criteria. </returns>
        protected virtual string loadCriteria(SearchCriteria searchCriteria)
        {
            //return searchCriteria.ToString();
            DateTime asOfDate = (DateTime)((DataSet)cachePolicy.GetCachedObject(RefreshDatesControlKey)).Tables[0].Rows[0]["salaryAsOfDate"];
            return string.Format(
                "{0}"
                , "Last Salary Post|" + asOfDate.ToShortDateString() + ";"
            );

        }

        protected virtual string getXMLDataWithSchema(DataSet rptSource)
        {
            StringWriter sw = new StringWriter();
            rptSource.WriteXml(sw, XmlWriteMode.WriteSchema);
            return sw.ToString();
        }

        #region process dataset null values
        protected void processDSNullField()
        {
            foreach (DataTable dt in rptSource.Tables)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    foreach (DataColumn dc in dt.Columns)
                    {
                        if (dr[dc.ColumnName] == System.DBNull.Value)
                        {
                            switch (dc.DataType.ToString())
                            {
                                case "System.DateTime":
                                    dr[dc.ColumnName] = System.DateTime.MinValue;
                                    //dc.DefaultValue = System.DateTime.MinValue;
                                    break;
                                case "System.Int32":
                                case "System.Decimal":
                                    dr[dc.ColumnName] = 0;
                                    //dc.DefaultValue = 0;
                                    break;
                                default:
                                    dr[dc.ColumnName] = "";
                                    //dc.DefaultValue="";
                                    break;
                            }
                        }

                    }
                }
            }
        }
        #endregion

        /// <summary>
        /// register new parameter to report
        /// </summary>
        protected void registerParameter()
        {
            throw new System.NotImplementedException();
        }

        /// <summary>
        /// Adds refresh dates currently visible on the page to the search criteria string
        /// to be passed down to reports. The criteria does not persist to the SearchCriteria
        /// object.
        /// </summary>
        /// <param name="searchCriteria">Object containing search criteria.</param>
        /// <returns>A string representation of search criteria. </returns>
        protected string AddRefreshDatesToCriteria()
        {
            StringBuilder criteria = new StringBuilder(searchCriteria.ToString(";"));
            criteria.AppendFormat("Last Salary Post|{0};", SalaryAsOfDate.ToShortDateString());
            criteria.AppendFormat("Last GL Post|{0};", glPostAsOfDate.ToShortDateString());
            criteria.AppendFormat("Last PO/AP Post|{0};", POAPAsOfDate.ToShortDateString());
            return criteria.ToString();
        }

    }
}
